package com.guchenbo.example.dubbo;

import com.guchenbo.example.dubbo.rpc.manual.ConsumerInvoker;
import com.guchenbo.example.dubbo.rpc.manual.ProviderInvoker;
import com.guchenbo.example.dubbo.rpc.manual.WorkerInvoker;
import com.guchenbo.example.dubbo.rpc.proxy.JdkProxyFactory;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.*;
import org.junit.Test;

import java.lang.reflect.Method;

/**
 * 去除dubbo的透明性，最原始的rpc调用
 */
public class ManualRpcTest extends DubboBaseTest {

  @Test
  public void allManual() throws Throwable {
    //手动关联消费者、服务者、实现者

    URL url = new URL("test", "", 1);

    Invoker<EchoService> worker = new WorkerInvoker<>(type, url, proxy);
    Invoker<EchoService> provider = new ProviderInvoker<>(type, url, worker);
    Invoker<EchoService> consumer = new ConsumerInvoker<>(type, url, provider);

    Method method = type.getMethod("echo", String.class);
    String str = "hello";
    Object[] arguments = new Object[]{str};
    Invocation invocation = new RpcInvocation(method, type.getName(), arguments);
    Result result = consumer.invoke(invocation);
    System.out.println(result.recreate());
  }

  private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class)
      .getExtension("gcb");

  @Test
  public void test() throws Throwable {
    URL url = new URL("test", "", 1, type.getName());

    Invoker<EchoService> worker = new WorkerInvoker<>(type, url, proxy);
    Invoker<EchoService> provider = new ProviderInvoker<>(type, url, worker);
    protocol.export(provider);

    Invoker<EchoService> consumer = protocol.refer(type, url);

    Method method = type.getMethod("echo", String.class);
    String str = "hello";
    Object[] arguments = new Object[]{str};
    Invocation invocation = new RpcInvocation(method, type.getName(), arguments);
    Result result = consumer.invoke(invocation);
    System.out.println(result.recreate());
  }

  @Test
  public void testWithAutoProxy() throws Throwable {
    //加入代理
    URL url = new URL("test", "", 1, type.getName());

    Invoker<EchoService> provider = JdkProxyFactory.getInvoker(type, url, proxy);
    protocol.export(provider);

    Invoker<EchoService> consumer = protocol.refer(type, url);
    EchoService service = JdkProxyFactory.getProxy(consumer);
    System.out.println(service.echo("hello"));
  }
}
